package handlers

import (
	"car-trade-hub/cache"
	"car-trade-hub/models"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func BigCarOrderList(c *gin.Context) {
	/*
		SELECT
		  big_car_orders.id AS OrderId,
		  big_car_orders.order_code AS OrderCode,
		  big_car_orders.order_price AS OrderPrice,
		  big_cars.car_code AS CarCode,
		  big_cars.car_name AS CarName,
		  big_cars.car_price AS CarPrice
		FROM
		  big_car_orders
		  LEFT JOIN big_cars ON big_cars.id = big_car_orders.cid
	*/
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var orderList []models.BigCarOrderList
	redis_key := "big_car_list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("big_car_orders").
			Select(
				"big_car_orders.id AS OrderId",
				"big_car_orders.order_code AS OrderCode",
				"big_car_orders.order_price AS OrderPrice",
				"big_cars.car_code AS CarCode",
				"big_cars.car_name AS CarName",
				"big_cars.car_price AS CarPrice",
			).Joins("LEFT JOIN big_cars ON big_cars.id = big_car_orders.cid").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&orderList)
		jsonData, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderList)
	}
	var total int64
	models.DB.Model(&models.BigCarOrder{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  orderList,
		"total": total,
	})
	return
}
func BigCarOrderDetail(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		  big_car_orders.id AS OrderId,
		  big_car_orders.order_code AS OrderCode,
		  big_car_orders.order_price AS OrderPrice,
		  big_cars.car_code AS CarCode,
		  big_cars.car_name AS CarName,
		  big_cars.car_price AS CarPrice
		FROM
		  big_car_orders
		  LEFT JOIN big_cars ON big_cars.id = big_car_orders.cid
		WHERE
		  big_car_orders.id = 1
	*/
	var orderList []models.BigCarOrderList
	redis_key := "big_car_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("big_car_orders").
			Select(
				"big_car_orders.id AS OrderId",
				"big_car_orders.order_code AS OrderCode",
				"big_car_orders.order_price AS OrderPrice",
				"big_cars.car_code AS CarCode",
				"big_cars.car_name AS CarName",
				"big_cars.car_price AS CarPrice",
			).Joins(" LEFT JOIN big_cars ON big_cars.id = big_car_orders.cid").
			Where("big_car_order.id=?", id).
			Debug().Find(&orderList)
		jsonData, _ := json.Marshal(orderList)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &orderList)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": orderList,
	})
	return
}
